﻿using CommonTools;
using Flurl.Http;
using shop.Bll;
using shop.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using unvell.ReoGrid;
using static unvell.Common.Win32Lib.Win32;

namespace shop.daifa
{
    /// <summary>
    /// 保存登记序号,
    /// 下载
    /// 放大图片
    /// 权限
    /// 粘贴功能
    /// 拖拽功能
    /// </summary>
    public partial class RefundImgPanel : FlowLayoutPanel
    {
        public int DocId { get; set; }

        private Lazy<RefundRegistBll> _bll = new Lazy<RefundRegistBll>(() => new RefundRegistBll());
        private Lazy<IFlurlClient> _client = new Lazy<IFlurlClient>(()=> myApp.GetClient());


        private AddImgBox _addBtn;



        public RefundImgPanel()
        {
            InitializeComponent();

            this.TabStop = true;
            this.AutoScroll = true;

            _addBtn = new AddImgBox(this);
            //_addBtn.Click += _addBtn_Click;
            this.Controls.Add(_addBtn);

            this.deleteMenuItem1.Click += DeleteMenuItem1_Click;
            this.下载MenuItem1.Click += 下载MenuItem1_Click;
            this.PasteMenuItem.Click += PasteMenuItem_Click;
        }

        private async void PasteMenuItem_Click(object sender, EventArgs e)
        {
            await WaitUI.RunAsync(async () =>
            {
                await this.UploadFromClipboard();
            });

        }

        private async void 下载MenuItem1_Click(object sender, EventArgs e)
        {
            if (sender is ToolStripMenuItem menu && (menu.Owner is ContextMenuStrip toolStrip))
            {
                if (toolStrip.SourceControl.Tag is RefundRegistImage item)
                {
                    var dialog = new SaveFileDialog()
                    {
                        Title = "保存图片",
                        FileName = item.FileName,
                        DefaultExt = Path.GetExtension(item.FileName),
                        AddExtension = true,
                    };

                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        var res = await _client.Value.Request("RefundRegist/Download")
                           .AppendQueryParam("fileName", item.ImgUlr)
                           .DownloadFileAsync(Path.GetDirectoryName(dialog.FileName), Path.GetFileName(dialog.FileName));
                    }
                }
            }
        }

        private async void DeleteMenuItem1_Click(object sender, EventArgs e)
        {
            if(sender is ToolStripMenuItem menu && (menu.Owner is ContextMenuStrip toolStrip) )
            {
                if(toolStrip.SourceControl.Tag is RefundRegistImage item)
                {
                    toolStrip.SourceControl.Parent = null;
                    await _bll.Value.DeleteItem(item);
                }
            }
        }




        /// <summary> 上传前检查 </summary>
        public Func<Result> BeforeUpload { set; get; }
        

        private async void _addBtn_Click(object sender, EventArgs e)
        {
            var res = BeforeUpload?.Invoke();

            if (res?.IsOk ==  false)
            {
                MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            await Upload();
        }




        /// <summary>  </summary>
        public async Task GetImages()
        {
            if (DocId <= 0)
            {
                return;
            }

            //var dir = myApp.GetDownloadDir();
            //if (string.IsNullOrEmpty(dir))
            //{
            //    return;
            //}

            this.Controls.Clear();

            //var dirInfo = new DirectoryInfo(Path.Combine(dir, "退换货图片"));
            //if (dirInfo.Exists == false)
            //{
            //    dirInfo.Create();
            //}

            var itmes = await _bll.Value.GetImagesUlrs(DocId);


            int i = 0;

            foreach (var item in itmes)
            {
                if (string.IsNullOrEmpty(item.ImgUlr))
                {
                    continue;
                }

                var name = item.ImgUlr.Substring(item.ImgUlr.LastIndexOf('/') + 1);

                this.Controls.Add(CreateBox(i,item));

                (this.Controls["pic" + i] as PictureBox).ImageLocation =_client.Value.BaseUrl+ "RefundRegist/Download?fileName=" + item.ImgUlr;

                i++;
            }


            this.Controls.Add(_addBtn);

        }

        private async void RefundImgPanel_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if ((Control.ModifierKeys & Keys.Control) == Keys.Control && e.KeyCode == Keys.V)//判断Ctrl+V键
            {
                await WaitUI.RunAsync(async () =>
                {
                    await UploadFromClipboard();
                });
            }    

        }

        /// <summary> 创建控件对象 </summary>
        private PictureBox CreateBox(int j, RefundRegistImage imgItem)
        {
            var box = new PictureBox()
            {
                Name = "pic" + j,
                Size = new Size(234, 285),
                InitialImage = Properties.Resources.loading4,
                SizeMode = PictureBoxSizeMode.Zoom,
                ContextMenuStrip = this.contextMenuStrip1,
                Tag = imgItem,
                BorderStyle = BorderStyle.Fixed3D,
            };

            box.DoubleClick += Box_DoubleClick;
            return box;
        }

        private Dictionary<int, Form> _imgForms;

        private void Box_DoubleClick(object sender, EventArgs e)
        {
            if (_imgForms == null) _imgForms = new Dictionary<int, Form>();

            var id = ((sender as PictureBox).Tag as RefundRegistImage).id;

            if (!_imgForms.ContainsKey(id) )
            {
                var form = new Form()
                {
                    Size = new Size(787, 735),
                    StartPosition = FormStartPosition.CenterScreen,
                    Text= ((sender as PictureBox).Tag as RefundRegistImage).FileName,
                };

                form.Controls.Add(new PictureBox() { Dock = DockStyle.Fill, Image = (sender as PictureBox).Image, SizeMode = PictureBoxSizeMode.Zoom });
                form.FormClosing += (s, e2) => _imgForms.Remove(id);
                form.KeyPreview = true;
                form.KeyDown += (s, e2) => { if (e2.KeyCode == Keys.Escape) form.Close(); };

                _imgForms.Add(id, form);
            }

            _imgForms[id].Show();
            _imgForms[id].Activate();
        }


        /// <summary> 添加一个 </summary>
        private void AddBox(Image img, RefundRegistImage item)
        {
            int i=0;
            foreach (Control box in this.Controls)
            {
                if(box.Name.StartsWith("pic") )
                {
                    int j =box.Name.Substring(3).IsNull(0);
                    i= Math.Max(i,j); 
                }
            }

            i++;

            this.Controls.Remove(_addBtn);
            var pictureBox = CreateBox(i, item);
            pictureBox.Image = img;

            this.Controls.Add(pictureBox);

            Controls.Add(_addBtn);
        }


        public async Task<bool> UploadFromClipboard(bool isKey= false)
        {
            List<RefundRegistImage> imgs = new List<RefundRegistImage>();

            if(Clipboard.ContainsImage())
            {
                var pic = Clipboard.GetImage();
                
                var img = new RefundRegistImage()
                {
                    Img = pic,
                    FileName = this.DocId+"_"+ Guid.NewGuid().ToString("N")+"."+GetExtenName(pic),
                    Isdel= false, DocId = this.DocId, 

                };
                img.ImgUlr = img.FileName;
                imgs.Add(img);
            }
            else if (Clipboard.ContainsFileDropList()) 
            {
                foreach (var item in Clipboard.GetFileDropList())
                {
                    if(item.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)
                        || item.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase)
                        || item.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)
                        || item.EndsWith(".png", StringComparison.OrdinalIgnoreCase)
                        || item.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)
                        || item.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)
                        )
                    {
                        if (File.Exists(item))
                        {
                            var img = new RefundRegistImage()
                            {
                                Img = Image.FromFile(item),
                                FileName = Path.GetFileName(item),
                                ImgPath = item,
                            };
                            img.ImgUlr = this.DocId + "_" + Guid.NewGuid().ToString("N")+"_"+img.FileName;
                            imgs.Add(img);
                        }
                    }
                  
                } 
            }
            //else if (Clipboard.ContainsText())
            //{
            //    var str = Clipboard.GetText();  
            //    if(str != null )
            //    {
            //        var tempPath = System.IO.Path.GetTempPath();

            //        var arr = str.Split(' ', ',', ';','，','　','；');
            //        foreach (var item in arr)
            //        {
            //            if (item.StartsWith("http"))
            //            {
            //                //var name = item.Substring(item.LastIndexOf('/'));

            //                var res = await item.DownloadFileAsync(tempPath, null);

            //                var img = new RefundRegistImage()
            //                {
            //                    Img = Image.FromFile(res),
            //                    FileName = Path.GetFileName(res),
            //                    ImgPath = res,
            //                    Isdel = false,
            //                    DocId = this.DocId,
            //                };
            //img.ImgUlr = this.DocId + "_" + Guid.NewGuid().ToString("N") + "_" + img.FileName;
            //                imgs.Add(img);
            //            }
            //        }
            //    }
            //}



            if (imgs.Count> 0)
            {
                var res = BeforeUpload?.Invoke();

                if (res?.IsOk == false)
                {
                    if (res?.IsOk == false)
                    {
                        if (!isKey)
                        {
                            MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        return false;
                    }
                    return false;
                }

                if (RightHelper.CheckRight("03.11.2") == false)
                {
                    //MessageBox.Show("对不起, 您没有权限!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }

                return await SaveItems(imgs);
            }
            else
            {
                return false;
            }
        }

        private int GetMaxId()
        {
            int i = 0;

            foreach (Control box in Controls)
            {
                if(box.Tag is RefundRegistImage img)
                {
                    i = Math.Max(i, img.ItemId);
                }
            }

            return i + 1;
        }

        private string GetExtenName(Image img)
        {
            if(img.RawFormat.Equals(ImageFormat.Jpeg))
            {
                return "jpg";
            }
            else if (img.RawFormat.Equals(ImageFormat.Bmp))
            {
                return "bmp";
            }
            else if (img.RawFormat.Equals(ImageFormat.Png))
            {
                return "png";
            }
            else if (img.RawFormat.Equals(ImageFormat.Gif))
            {
                return "gif";
            }
            else if (img.RawFormat.Equals(ImageFormat.Icon))
            {
                return "ico";
            }

            else if (img.RawFormat == ImageFormat.Bmp)
            {
                return "bmp";
            }
            else if (img.RawFormat == ImageFormat.Png)
            {
                return "png";
            }
            else
            {
                return "bmp";
            }
        }


        public async Task<bool> Upload()
        {
            if (RightHelper.CheckRight("03.11.2") == false)
            {
                MessageBox.Show("对不起, 您没有权限!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            var dialog = new OpenFileDialog()
            {
                Multiselect = true,
                //Filter = "图片 JPEG|*.jpeg;*.jpg|图片 PNG|*.png|位图 BMP|*.bmp|动图 GIF|*.gif|所有文件|*.*",
                Filter = "图片|*.jpeg;*.jpg;*.png;*.bmp;*.gif",
                Title = "上传图片"
            };


            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var items = dialog.FileNames
                    .Select(a => new RefundRegistImage()
                    {
                        ImgUlr = DocId.ToString() + "_" + Guid.NewGuid().ToString("N")+"_"+ Path.GetFileName(a),
                        ImgPath = a,
                        FileName= Path.GetFileName( a),
                    })
                    .ToArray();

                return await WaitUI.RunAsync( async ()=> 
                    await SaveItems(items)
                    );
            }
            else
            {
                return false;
            }
        }


        private async Task<bool> SaveItems(IEnumerable<RefundRegistImage> items)
        {
            var itemid = GetMaxId();

            foreach (var item in items)
            {
                item.DocId = DocId;
                item.ItemId = itemid++;
                item.Isdel = false;

                if (string.IsNullOrEmpty(item.ImgPath))
                {
                    item.ImgPath = Path.GetTempFileName();
                    item.Img.Save(item.ImgPath);
                }


                // 多次尝试
                bool success = false;
                Exception ex= null;
                for (int i = 0; i < 5; i++)
                {
 
                    try
                    {
                        await _client.Value.Request("RefundRegist/Upload")
                        .PostMultipartAsync(mp => mp
                            .AddFile("file", item.ImgPath, null, 4096, item.ImgUlr)
                        );


                        //throw new Exception("2");

                        success = true;
                        break;
                    }
                    catch (Exception ex1)
                    {
                        ex = ex1;
                    }

                    if (!success)
                    {
                        await Task.Delay(800);
                    }
                }

                if (!success && ex != null)
                {
                    throw ex;
                }



                AddBox(Image.FromFile(item.ImgPath), item);
            }

            await _bll.Value.SaveImages(items);
            return true;
        }


        private async void RefundImgPanel_DragDrop(object sender, DragEventArgs e)
        {
            if (RightHelper.CheckRight("03.11.2") == false)
            {
                MessageBox.Show("对不起, 您没有权限!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            List<RefundRegistImage> items = new List<RefundRegistImage>();

            // 从DragEventArgs中获取图像
            if (e.Data.GetDataPresent(DataFormats.Bitmap))
            {
                // 获取图像
                Bitmap droppedImage = (Bitmap)e.Data.GetData(DataFormats.Bitmap);

                items.Add( new RefundRegistImage()
                {
                    Img = droppedImage,
                    ImgUlr = DocId.ToString() + "_" + Guid.NewGuid().ToString("N")+".bmp",
                });
                items[items.Count - 1].FileName = items[items.Count - 1].ImgUlr;
            }
            else if(e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                // 从DragEventArgs中获取文件路径
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                // 对每个文件执行操作
                items = files.Select(a=> new RefundRegistImage()
                {
                    Img= Image.FromFile(a), 
                    ImgPath= a,
                    FileName= Path.GetFileName( a),
                    ImgUlr= DocId.ToString() + "_" + Guid.NewGuid().ToString("N")+"_"+Path.GetFileName(a),
                })
                    .ToList();

            }

            if(items.Count > 0)
            {
                await WaitUI.RunAsync( async () =>
                    await SaveItems(items)
                );
            }


        }

        private void RefundImgPanel_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect= DragDropEffects.Copy;
        }
    }
}
